# -*- coding: utf-8 -*-
import hashlib
import json
import time

import requests
import xmltodict
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '866376110023229': {
        'API_KEY': '6ef1d38c3dd8d9f26eb7cc0f08c6ebfc',
        'gateway': 'http://cloud.eatongpay.com/cgi-bin/netpayment/pay_gate.cgi',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def verify_notify_sign(params, key):
    sign = params.pop('signMsg')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("yiantongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def generate_sign(d, key):
    '''  生成下单签名 '''
    s = 'apiName={}&apiVersion={}&platformID={}&merchNo={}&orderNo={}&tradeDate={}&amt={}&merchUrl={}&merchParam={}&tradeSummary={}{}'.format(
        d['apiName'], d['apiVersion'], d['platformID'], d['merchNo'], d['orderNo'], d['tradeDate'], d['amt'],
        d['merchUrl'], d['merchParam'], d['tradeSummary'], key
    )
    _LOGGER.info("yiantongpay sign str: %s ", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_notify_sign(d, key):
    '''  生成下单签名 '''
    s = 'apiName={}&notifyTime={}&tradeAmt={}&merchNo={}&merchParam={}&orderNo={}&tradeDate={}&accNo={}&accDate={}&orderStatus={}{}'.format(
        d['apiName'], d['notifyTime'], d['tradeAmt'], d['merchNo'], d['merchParam'], d['orderNo'], d['tradeDate'],
        d['accNo'], d['accDate'], d['orderStatus'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_query_sign(d, key):
    '''  生成下单签名 '''
    s = 'apiName={}&apiVersion={}&platformID={}&merchNo={}&orderNo={}&tradeDate={}&amt={}{}'.format(
        d['apiName'], d['apiVersion'], d['platformID'], d['merchNo'], d['orderNo'], d['tradeDate'], d['amt'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['signMsg']
    params.pop('signMsg')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("yiantongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 1.  网银
# 4.  支付宝扫码
# 5.  微信扫码
# 6.  QQ扫码
# 8.  京东扫码
# 9.  支付宝H5(WAP_PAY_B2C)
# 10. 支付宝WAP(WAP_PAY_B2C)
# 11. 微信WAP(WAP_PAY_B2C)
# 12. 平台快捷
# 13. 微信H5(WAP_PAY_B2C)
# 17. 银联扫码
# 28.QQWAP(WAP_PAY_B2C) 14
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '13'
    elif service == 'alipay':
        payType = '9'
    elif service == 'qq':
        payType = '14'
    else:
        payType = '12'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    p_dict = {
        'apiName': 'WAP_PAY_B2C',
        'apiVersion': '1.0.0.0',
        'platformID': mch_id,
        'merchNo': mch_id,
        'orderNo': str(pay.id),
        'tradeDate': time.strftime("%Y%m%d"),
        'amt': str(pay_amount),
        'merchUrl': '{}/pay/api/{}/yiantongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'merchParam': '123',
        'tradeSummary': 'charge',
        # 'customerIP': _get_device_ip(info),
    }
    p_dict['signMsg'] = generate_sign(p_dict, key)
    p_dict['choosePayType'] = _get_pay_type(service)
    p_dict['bankCode'] = ''
    _LOGGER.info("yiantongpay create date: %s", p_dict)
    html_text = _build_form(p_dict, _get_gateway(mch_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("yiantongpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('yiantongpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['orderStatus'])
    trade_no = data['accNo']
    total_fee = float(data['tradeAmt'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # 0 未支付，1 成功，2失败
    if trade_status == 1:
        _LOGGER.info('yiantongpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'apiName': 'MOBO_TRAN_QUERY',
        'apiVersion': '1.0.0.0',
        'platformID': app_id,
        'merchNo': app_id,
        'orderNo': str(pay_id),
        'tradeDate': pay_order.created_at.strftime('%Y%m%d'),
        'amt': str(pay_order.total_fee),
    }
    p_dict['signMsg'] = generate_query_sign(p_dict, key)
    _LOGGER.info(u'yiantongpay query data: %s', p_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info(u'yiantongpay query rsp: %s', response.text)
    data = xmltodict.parse(response.text)['moboAccount']['respData']
    if response.status_code == 200:
        trade_status = int(data['Status'])
        total_fee = float(pay_order.total_fee)
        trade_no = data['accNo']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0 - 未支付1 - 成功2 - 失败
        # 4 - 部分退款5 - 全额退款
        # 9 - 退款处理中10 - 未支付
        # 11 - 订单过
        if trade_status == 1:
            _LOGGER.info('yiantongpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('yiantongpay data error, status_code: %s', response.status_code)
